package com.joyxy.easy.entity;

import cn.sanenen.dm.base.DmApi;
import cn.sanenen.dm.base.DmApiCache;
import cn.sanenen.dm.common.Constant;
import com.joyxy.easy.monitor.AutomationRunner;
import com.joyxy.easy.monitor.StatusMonitor;

public class WindowContext {
    private final long hwnd;
    private final DmApi dmApi;
    private final StatusMonitor monitor;
    private boolean isActive;
    private AutomationRunner automationRunner;

    public WindowContext(long hwnd) {
        this.hwnd = hwnd;
        if("test".equals(Constant.ENV)){
            this.dmApi = DmApiCache.createNewInstance(hwnd); // 每个窗口独立实例
        }else{
            this.dmApi = DmApiCache.createNewInstance2(hwnd);
        }
        this.monitor = new StatusMonitor(hwnd, dmApi);

        // 绑定窗口
//        if (dmApi.BindWindow(hwnd, "dx", "windows", "windows", 0) != 1) {
//            throw new RuntimeException("窗口绑定失败");
//        }
        if (dmApi.BindWindow(hwnd, "gdi", "dx2", "windows", 0) != 1) {
            throw new RuntimeException("窗口绑定失败");
        }

    }

    public void startMonitoring() {
        monitor.start();
        isActive = true;
    }

    public void stopMonitoring() {
        if(monitor != null){
            monitor.stop();
        }
        isActive = false;
    }

    // Getters
    public long getHwnd() {
        return hwnd;
    }

    public StatusMonitor getMonitor() {
        return monitor;
    }

    public boolean isActive() {
        return isActive;
    }

    public DmApi getDmApi() {
        return dmApi;
    }

    public AutomationRunner getAutomationRunner() {
        return automationRunner;
    }

    public void setAutomationRunner(AutomationRunner automationRunner) {
        if(this.automationRunner != null){
            this.automationRunner.stop();
        }
        this.automationRunner = automationRunner;
        automationRunner.start();
    }

    public void stop() {
        stopMonitoring();
        if(automationRunner != null){
            automationRunner.stop();
        }
        isActive = false;
    }
}
